from flask import Flask
from flask import request
from bilibili_api import sync,bangumi,search
from bilibili_api.bangumi import IndexFilter as IF
from datetime import datetime
from flask_cors import CORS

app = Flask(__name__)
CORS(app, resources=r'/*')

@app.route("/")
def hello():
    return 'hello'

# 获取周更新列表
@app.route("/get_dailyList")
def get_dailyList():
    week = datetime.date(datetime.today()).isoweekday()
    return sync(bangumi.get_timeline(bangumi.BangumiType(1), week-1, 7-week))

# 番剧列表索引
@app.route("/filter")
def get_filterList():
    area = request.args.get("area")
    status = request.args.get("status")
    year = request.args.get("year")
    style = request.args.get("style")
    order = request.args.get("order")
    page = request.args.get("page")
    print(area,status,year,style,order,page)
    filters = bangumi.IndexFilterMeta.Anime(area=area,finish_status=status,year=IF.make_time_filter(start=year, end=str(int(year)+1)),style=style)
    if(year == '-1'):
        filters = bangumi.IndexFilterMeta.Anime(area=area,finish_status=status,year=IF.make_time_filter(start=year, end=year),style=style)
    if(order == '3'):
        index = sync(bangumi.get_index_info(filters=filters,order=IF.Order.FOLLOWER,sort=IF.Sort.DESC,pn=page,ps=24))
        return index
    if(order == '4'):
        index = sync(bangumi.get_index_info(filters=filters,order=IF.Order.SCORE,sort=IF.Sort.DESC,pn=page,ps=24))
        return index
    if(order == '2'):
        index = sync(bangumi.get_index_info(filters=filters,order=IF.Order.PLAY,sort=IF.Sort.DESC,pn=page,ps=24))
        return index

# 获取番剧详情
@app.route("/fanju")
def get_fanjuInfo():
    id = request.args.get("id")
    type = request.args.get("type")
    if(type == "ssid"):
        ##获取能获取到信息的id
        id = bangumi.Bangumi(ssid=id).get_media_id()
    return sync(bangumi.Bangumi(id).get_overview())

# 获取元数据
@app.route("/fanju_simple")
def get_fanju_simple():
    id = request.args.get("id")
    return sync(bangumi.Bangumi(id).get_meta())


#搜索番剧
@app.route("/search")
def toSearch():
    text = request.args.get("text")
    page = request.args.get("page")
    return sync(search.search_by_type(text,search_type=search.SearchObjectType.BANGUMI,page=page))

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8083, threaded=True)